<script setup>
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import http from '@/utils/http'
import CyIcon from '@/components/Icon.vue'
import { useAccurateTimer } from '@/utils/timer'
import CyPlayerCls from '@/utils/cy.player'
import { fetchMavMenus } from '@/api/role'
const { datetime, week, startAccurateTimer, stopAccurateTimer } = useAccurateTimer()
function getEventReal(params) {
    http.post('/login/logout', {}).then(res => {
        if (res.code == 1) {
            localStorage.clear()
            router.push({ path: '/login' })
        }
    })
}

getStyle()
const style = ref({})

function getStyle() {
    http.get('/common/style', {}).then(res => {
        if (res.code == 1) {
            style.value = res.data
            localStorage.setItem('mode', res.data.mode)
        }
    })
}

const router = useRouter()
const route = useRoute()
const accountUser = ref(JSON.parse(localStorage.getItem('user')) || { username: '' })

const isPanoramaPage = computed(() => {
    return route.meta?.panorama
})

const isNavigatorPage = computed(() => {
    return route.meta?.navigator
})

const isVideoPage = computed(() => {
    return route.meta?.video
})

const isMapPage = computed(() => {
    return route.meta?.map
})

const isVideoPage2 = computed(() => {
    return route.meta?.video2
})
/**
 * 递归获取最后一级菜单的地址
 * 该层菜单如含有 isPage = true 属性,则不跳转子页面,而使用当前页菜单
 */
const toUrl = (object, url) => {
    if (object.children && object.children.length > 0) {
        if (object.children[0].children && object.children[0].children.length > 0) {
            //if (!object.isPage && object.children[0].children) {
            toUrl(object.children[0])
        } else {
            router.push(object.children[0].url)
        }
    } else {
        router.push(url)
    }
}
const currentIndex = ref()
const warning_open = ref(true)
const toPage = (i, item) => {
    if (item.id == 17) {
        const cyPlayer = new CyPlayerCls()
        const data = {
            server_ip: localStorage.getItem('serverIp'),
            server_port: localStorage.getItem('serverPort'),
            uid: localStorage.getItem('uid')
        }
        cyPlayer.openLiveVideo(data)
        //cyPlayer.openPlayBack()
        return
    }
    //报警墙
    if (item.id == 129) {
        const cyPlayer = new CyPlayerCls()
        cyPlayer.openALarmWall()
        return
    }
    if (item.is_blank == 2) {
        //新页面打开
        window.open('/#' + item.url, '_blank')
        return
    }
    currentIndex.value = i
    localStorage.setItem('currentIndex', i)
    let object = null
    object = menu.value[i]
    if (object.children != 'undefined') {
        localStorage.setItem('menu_child', JSON.stringify(object.children))
    }
    toUrl(object, item.url)
}
const passForm = ref({})
const handleCommand = cmd => {
    switch (cmd) {
        case 'logout':
            getEventReal()

            break
        case 'changePassword':
            editPassShow.value = true
            passForm.value = {}
    }
}
const editPassShow = ref(false)
const menu = ref([])
const routers = useRouter()
const formRef = ref(null)
const rules = reactive({
    //定义验证规则，有两种方式：
    //1.使用ele原生的验证规则。
    old_pass: [{ required: true, message: '请输入原始密码', trigger: 'blur' }],
    password: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
    re_pass: [{ required: true, message: '请输入确认密码', trigger: 'blur' }]
})
const onSubmit = () => {
    formRef.value.validate(valid => {
        if (valid) {
            var data = passForm.value
            data.id = localStorage.getItem('uid')
            http.post('/v1/account/pass', data).then(res => {
                if (res.code == 1) {
                    ElMessage.success('更新成功,重新登录')
                    setTimeout(() => {
                        router.push({ path: '/login' })
                    }, 2000)
                }
            })
        }
    })
}
const openWarning = (is_open) => {
    warning_open.value = is_open
    localStorage.setItem('warning_open', is_open)
}
const navToPageJson = ref([
    '/setting/map',
    '/event/basic',
    '/log/fail',
    '/position/leave',
    '/resource/snap/face',
    '/position/leave',
])
watch(
    () => routers.currentRoute.value.fullPath,
    (newValue, oldValue) => {
        /***
         * @description 初始化没有地图,从电子地图跳转到地图管理
         * @description 从电子地图跳转到事件管理
         * @description 从综合态势跳转到系统故障日志
         * @description 从综合态势跳转到人员离岗
         * @description 从大华人脸识别跳转到事件中心
         * @description 从大华人脸识别跳转到人脸抓拍
        */
        if (navToPageJson.value.includes(newValue)) {
            checkMenu(newValue)
        }
        // console.log('newValue', newValue)
        // console.log('oldValue', oldValue)

        // if ((oldValue == '/map' && newValue == '/setting/map') ||
        //     (oldValue == '/map' && newValue == '/event/basic') ||
        //     (oldValue == '/main' && newValue == '/log/fail')) {
        //     currentIndex.value = localStorage.getItem('currentIndex')
        // }
        // /**
        //  * @description 从大华人脸识别跳转到事件中心
        //  * @description 从大华人脸识别跳转到人脸抓拍
        //  * */
        // if (newValue == '/position/leave') {
        //     currentIndex.value = null
        // }
        // if (newValue == '/event/basic' || newValue == '/resource/snap/face') {
        //     checkMenu(newValue)
        // }
    }
)
/**
 * @description 获取当前菜单的index
 * @param {*} path
 * @param {*} menus
 * @returns
 * */
const findMenuIndex = (path, menus) => {
    return menus.findIndex(item => {
        if (item.url && path === item.url) return true
        return item.children?.some(child => {
            if (child.url && path.includes(child.url)) return true
            return child.children?.some(grandchild => grandchild.url && path.includes(grandchild.url))
        })
    })
}
const checkMenu = (nowPath) => {
    menu.value = JSON.parse(localStorage.getItem('menu'))
    let foundIndex = findMenuIndex(nowPath, menu.value)
    let item
    if (foundIndex !== -1) {
        currentIndex.value = foundIndex
        item = menu.value[foundIndex] || {}
        if (Object.keys(item).length == 0) {
            return
        }
        localStorage.setItem('menu_child', JSON.stringify(item.children))
        return
    }
    currentIndex.value = null
    const navMenus = JSON.parse(localStorage.getItem('navMenus'))
    foundIndex = findMenuIndex(nowPath, navMenus)
    if (foundIndex == -1) {
        return
    }
    item = navMenus[foundIndex] || {}
    if (Object.keys(item).length == 0) {
        return
    }
    localStorage.setItem('menu_child', JSON.stringify(item.children))
}
const initMenucurrent = () => {
    const nowPath = routers.currentRoute.value.fullPath
    checkMenu(nowPath)
}
initMenucurrent()
onMounted(() => {
    startAccurateTimer()
    initMenus()
})

onUnmounted(() => {
    stopAccurateTimer()
})
const toNavPage = () => {
    currentIndex.value = null
    localStorage.setItem('currentIndex', null)
    router.push({ path: '/navigation' })
}
const navMenus = ref([])
const initMenus = async () => {
    if (!localStorage.getItem('navMenus')) {
        const result = await fetchMavMenus()
        localStorage.setItem('navMenus', JSON.stringify(result.data))
        navMenus.value = result.data
    } else {
        navMenus.value = JSON.parse(localStorage.getItem('navMenus'))
    }
}
</script>
<template>
    <el-container class="layout-window" :panorama-page="isPanoramaPage ? '' : null"
        :navigator-page="isNavigatorPage ? '' : null">
        <el-header class="layout-header" :panorama-page="isPanoramaPage ? '' : null">
            <div class="header-logo">
                <p>{{ style.name || '生产指挥中心综合安防平台' }}</p>
            </div>
            <div class="header-nav">
                <ul>
                    <template :key="index" v-for="(item, index) in menu">
                        <li :class="{ 'active': currentIndex == index }" @click="toPage(index, item)">
                            <cy-icon :code="item.icon" :size="16" />
                            <span>{{ item.name }}</span>
                        </li>
                    </template>
                </ul>
            </div>
            <div class="flex-center">
                <cy-icon v-if="navMenus.length" code="&#xe6be;" :size="20" class="linear-gradient"
                    style="cursor: pointer;" @click="toNavPage" />
            </div>
            <div class="flex-center">
                <el-dropdown @command="handleCommand" trigger="click">
                    <cy-icon code="&#xe614;" :size="20" class="linear-gradient" />
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item>{{ accountUser.username }}</el-dropdown-item>
                            <el-dropdown-item>版本号({{ style.version }})</el-dropdown-item>
                            <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
                            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
            <div class="line"></div>
            <div class="header-account">
                <div class="datetime">
                    <div class="date">
                        {{ datetime }}
                    </div>
                    <div class="time">
                        {{ week }}
                    </div>
                </div>
            </div>
        </el-header>
        <el-main class="layout-main">
            <router-view></router-view>
        </el-main>
    </el-container>
    <el-dialog v-model="editPassShow" title="修改密码" width="30%" :close-on-click-modal="false">
        <el-form :model="passForm" label-width="120px" ref="formRef" :rules="rules">
            <el-form-item label="原始密码" prop="old_pass">
                <el-input type="password" v-model="passForm.old_pass" style="width:70%;" placeholder="原始密码" />
            </el-form-item>
            <el-form-item label="新&nbsp;密&nbsp;码" prop="password">
                <el-input type="password" v-model="passForm.password" style="width:70%;" placeholder="新密码" />
            </el-form-item>
            <el-form-item label="确认密码" prop="re_pass">
                <el-input type="password" v-model="passForm.re_pass" style="width:70%;" placeholder="确认密码" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="editPassShow = false; passForm = {}">取消</el-button>
                <el-button type="primary" @click="onSubmit">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<style lang="scss" scoped>
.layout-window {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #F0F2F5;

    &[panorama-page] {
        background: #040850 url('../assets/board/all_bg.png') no-repeat;
        background-size: 100% 100%;
    }

    &[navigator-page] {
        background: #040850 url('@/assets/navigation/background.png') no-repeat;
        background-size: 100% 100%;
    }
}

.layout-main {
    flex: 1 0 0;
    width: 100%;
    height: 0;
    padding: 0;
}

.layout-header {
    box-sizing: border-box;
    display: flex;
    justify-content: flex-start;
    flex: 88px 0 0;
    padding: 0 40px 0 20px;
    background-color: rgb(0, 7, 20);
    //background-color: #040850;
    background-image: url('@/assets/board/headerbg1.png');
    background-size: 100%;
    background-repeat: no-repeat;
    padding-bottom: 16px;

    &[panorama-page] {
        background: url('@/assets/board/headerbg1.png');
        background-size: 100%;
        background-repeat: no-repeat;
    }
}

.header-logo {
    flex: 455px 0 0;
    //padding-top: 17px;
    font-family: YouSheBiaoTiHei, serif;
    font-weight: 400;
    font-size: 37px;
    color: #4891FF;
    line-height: 80px;
    background: linear-gradient(0deg, #4DD3FF 0%, #FFFFFF 100%);
    background-clip: text;
    -webkit-text-fill-color: transparent;

    //img {
    //    display: block;
    //    width: 488px;
    //    height: 42px;
    //}
}

.header-nav {
    flex: 1 0 0;
    display: flex;
    padding-top: 14px;
    font-family: Microsoft YaHei;

    & ul {
        display: flex;
        margin-left: -20px;
    }

    & li {
        display: flex;
        align-items: center;
        gap: 9px;
        box-sizing: border-box;
        flex: 178px 0 0;
        height: 40px;
        padding-left: 38px;
        background: url('../assets/header/nav-menu-base.png') no-repeat;
        background-size: contain;
        line-height: 1;
        font-size: 16px;
        font-weight: 400;
        color: #AEEBFF;
        cursor: pointer;
        user-select: none;

        & img {
            width: 20px;
            height: 20px;
        }

        & .st0 {
            fill: #3FC2FF !important;
        }

        &.active {
            background-image: url('../assets/header/nav-menu-on.png');
            font-weight: 500;
            color: #FFF;
        }

        &:not(:first-child) {
            margin-left: -12px;
        }
    }
}

.header-account {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    font-size: 16px;
    width: 170px;

    .divider {
        width: 2px;
        height: 30px;
        margin: 0 21px;
        background: #113A55;
    }

    .datetime {
        display: flex;
        flex-direction: column;
        margin-left: 22px;

        .date {
            font-family: PangMenZhengDao, serif;
            font-weight: 400;
            font-size: 16px;
            color: #5B7CB3;
            line-height: 16px;
        }

        .time {
            font-family: PangMenZhengDao, serif;
            font-weight: 400;
            font-size: 23px;
            color: #9FCEFF;
            line-height: 23px;
        }
    }
}

.avatar {
    width: 20px;
    height: 20px;
    margin-right: 6px;
}

.ld-icon {
    width: 30px;
    height: 30px;
    margin-right: 6px;
    cursor: pointer;
}

.user-name {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-right: 20px;

    .user-name-label {
        font-size: 12px;
    }

    .user-name-number {
        margin-top: 5px;
        font-size: 13px;
    }
}

.el-dropdown-link {
    min-width: 80px;
    max-width: 140px;
    color: #39D6FE;
    cursor: pointer;
    font-size: 16px;
    font-weight: 700;
    text-align: center;
}

.dropdown-arrow {
    margin-left: 6px;
}

.dropdown-icon {
    width: 50px;
    height: 50px;
}

.flex-center {
    display: flex;
    align-items: center;
    margin-right: 20px;
}

.line {
    width: 2px;
    height: 30px;
    background: #113A55;
    margin-top: 20px;
    margin-right: 10px;
}

.linear-gradient {
    background: linear-gradient(146deg, #26378A 0%, #7AE4FF 99%);
    -webkit-background-clip: text;
    color: transparent;
}
</style>
